
import java.io.File;
import java.io.FileOutputStream;
import java.util.jar.Attributes;
import java.util.jar.Manifest;

public class ManifestUtil {
	
	public static void main(String[] args){
		try {
			ManifestUtil.createManifest("C:\\Users\\Darkness\\Desktop\\abd-im\\ddMANIFEST.MF", "C:\\Users\\Darkness\\Desktop\\abd-im\\lib","lib","com.horse.StuManager");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 生成manifest文件
	 * @param filePath 保存manifest文件的路径+文件名，例如：c:/111/MANIFEST.MF
	 * @param jarDir 存放被引用jar的文件夹路径，例如：C:/111/lib
	 * @param classDirPre 相对路径，例如：如果被引用jar放在相对入口jar的lib文件夹里面，该参数就设置成"lib"；如果是平级，该参数可设置成空字符串或null
	 * @param mainClassPath 主函数路径，例如：com.horse.StuManager
	 * @throws Exception
	 */
	public static void createManifest(String filePath, String jarDir, String classDirPre,String mainClassPath)
			throws Exception {
		File mfFile = new File(filePath);
		if (!mfFile.exists()) {
			mfFile.createNewFile();
		}
		FileOutputStream fos = new FileOutputStream(mfFile);
		StringBuffer sb = new StringBuffer();
		File classFile = new File(jarDir);
		int count = 0;
		if (classFile.exists()) {
			if (classFile.isDirectory()) {
				File[] files = classFile.listFiles();
				for (int i = 0; i < files.length; i++) {
					if (files[i].getName().endsWith(".jar")) {
						count++;
						sb.append(((classDirPre==null || classDirPre.equals(""))?"" : (classDirPre + "/")) + files[i].getName()).append(" ");
					}
				}
			}
		}
		System.out.println("There are " + count + " jar files!");
//		System.out.println(sb.toString());
		Manifest m = new Manifest();
		Attributes a = m.getMainAttributes();
		a.put(Attributes.Name.MANIFEST_VERSION, "1.0");
		System.out.println("MANIFEST_VERSION=" + a.getValue(Attributes.Name.MANIFEST_VERSION));
		if(mainClassPath != null && !mainClassPath.equals("")){
			a.put(Attributes.Name.MAIN_CLASS, mainClassPath);
			System.out.println("MAIN_CLASS=" + a.getValue(Attributes.Name.MAIN_CLASS));
		}
		a.put(Attributes.Name.CLASS_PATH, sb.toString());
		System.out.println("CLASS_PATH=" + a.getValue(Attributes.Name.CLASS_PATH));
		m.write(fos);
		fos.flush();
		fos.close();
	}
}